package com.wjc.system.controller.admin;




import com.alibaba.fastjson.JSONObject;
import com.wjc.server.dto.CommonDto;
import com.wjc.server.dto.LoginUserDto;
import com.wjc.server.dto.PageDto;
import com.wjc.server.dto.UserDto;
import com.wjc.server.service.UserService;
import com.wjc.server.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/admin/user")
public class UserController {

    private static final Logger LOG= LoggerFactory.getLogger(UserController.class);
    public static final String BUSINESS_NAME = "用户";

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private SnowFlake snowFlake;

    //查询
    @GetMapping("/list")
    public CommonDto list(@Valid  PageDto pageDto){
         userService.list(pageDto);
//         LOG.info("分页有啥: {}",pageDto);
        CommonDto<PageDto> pageDtoCommonDto = new CommonDto<>();
        pageDtoCommonDto.setContent(pageDto);
        return pageDtoCommonDto;
    }

    //保存
    @PostMapping("/save")
    public CommonDto list(@Valid @RequestBody UserDto userDto){
        CommonDto commonDto=new CommonDto<>();
        //加密
        userDto.setPassword(DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes()));
        userService.save(userDto);
        return commonDto;

    }

    //修改密码
    @PostMapping("/save-password")
    public CommonDto savePassword(@Valid @RequestBody UserDto userDto){
        CommonDto commonDto=new CommonDto<>();
        //加密
        userDto.setPassword(DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes()));
        userService.savePassword(userDto);
        return commonDto;

    }

    //登录
    @PostMapping("/login")
    public CommonDto login(@Valid @RequestBody UserDto userDto){
        CommonDto commonDto=new CommonDto<>();

        //根据验证码token去获取缓存中的验证码对比用户输入的验证码是否一致
       //String imageCode= (String) request.getSession().getAttribute(userDto.getImageCodeToken());
        //改用redis存储
        String imageCode= (String) redisTemplate.opsForValue().get(userDto.getImageCodeToken());

        if(StringUtils.isEmpty(imageCode)){
            //若为空则说明session过期，验证码过期
            commonDto.setSuccess(false);
            commonDto.setMessage("验证码已过期");
            LOG.info("验证码过期");
            return commonDto;
        }
        if(!imageCode.toLowerCase().equals(userDto.getImageCode().toLowerCase())){
            //验证码错误
            commonDto.setSuccess(false);
            commonDto.setMessage("验证码错误");
            LOG.info("验证码错误");
            return commonDto;
        }else {
            //验证通过,移除验证码
//            request.getSession().removeAttribute(userDto.getImageCodeToken());
            redisTemplate.delete(userDto.getImageCodeToken());
        }

        //加密密码
        userDto.setPassword(DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes()));
        LoginUserDto loginuser = userService.login(userDto);

        //生成token
        Long token=snowFlake.nextId();
        loginuser.setToken(token.toString());
        //用户信息存入redis,有效期24小时
        redisTemplate.opsForValue().set(token.toString(), JSONObject.toJSONString(loginuser),3600*24, TimeUnit.SECONDS);

        commonDto.setContent(loginuser);
        return commonDto;
    }

    //退出登录
    @GetMapping("/logout/{token}")
    public CommonDto logout(@PathVariable  String token){
        CommonDto commonDto=new CommonDto<>();
        //删除token
        redisTemplate.delete(token);
        return commonDto;
    }


    //删除
    @DeleteMapping("/delete/{id}")
    public CommonDto delete(@PathVariable Long id){
        CommonDto commonDto=new CommonDto<>();
        userService.delete(id);
        return commonDto;
    }
}
